/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: Shentong
 * @LastEditTime: 2021-11-11 16:59:56
 */
/**
 * @description 此页面暂时不用： TODO:
 */
// eslint-disable-next-line @typescript-eslint/no-use-before-define
 import React, { useEffect, useState, useRef, useCallback } from "react";
import Taro, { useDidShow } from '@tarojs/taro'

 import { View, Image } from "@tarojs/components";

 import {  showToast, getStoregeByKey, userAPIAuthSeting } from '@/utils/index'

import { luckCardActivity, luckCardUserCount, submitCardActivity, wxPay, doDraw } from '@/api/order'

import RuleModal from "./components/rules";

import CloseIcon from '@/src/assets/activity/close.png'

import Pattern1 from '@/src/assets/activity/pattern1.png'
import Pattern2 from '@/src/assets/activity/pattern2.png'
import Pattern3 from '@/src/assets/activity/pattern3.png'
import Pattern4 from '@/src/assets/activity/pattern4.png'

import styles from './index.module.scss'

const Card1 = 'https://c.jlshuangcheng.com/static/images/card1.png'
const Card2 = 'https://c.jlshuangcheng.com/static/images/card2.png'

const prizeTypeObj = {
  0: '现金大奖',
  1: '商户优惠券',
  2: '平台红包'
}

const initPrize = {
  prize: false,
  prizeType: -1,
  name: ''
}



 const LuckCard = () => {
  const card = [
    {img: Pattern1, styles: {
     top:'140px', left: '250px'
    }},
    {img: Pattern2, styles: {
     top:'140px', left: '250px'
    }},
    {img: Pattern3, styles: {
     top:'140px', left: '250px'
    }},
    {img: Pattern4, styles: {
     top:'140px', left: '250px'
    }},
    {img: Pattern1, styles: {
     top:'140px', left: '250px'
    }},
    {img: Pattern2, styles: {
     top:'140px', left: '250px'
    }},
  ]

  const resetPosition = [
    {
      top:'0', left: '15px'
     },
     {
      top:'0', left: '135px'
     },
     {
      top:'0', left: '250px'
     },
     {
      top:'140px', left: '15px'
     },
     {
      top:'140px', left: '135px'
     },
     {
      top:'140px', left: '250px'
     }
  ]

  const [cardIndex, setCardIndex] = useState(-1)
  const [openIndex, setOpenIndex] = useState(-1)
  const [cardList, setCardList] = useState(card)
  const [isReset,  setIsReset] = useState(false)
  const [showCardMask, setShowCardMask] = useState(false)
  const [showResult, setShowResult] = useState(false)
  const [btnList, setBtnList] = useState([])
  const [useDrawCount, setUseDrawCount] = useState(0)
  const [lonAndlat, setLonAndlat] = useState({lon: 0, lat: 0})
  const [drawResult, setDrawResult] = useState(initPrize)
  const [showRuleModal, setShowRuleModal] = useState(false)
  const [schoolSId, setSchoolsId] = useState('')

  const timer = useRef<NodeJS.Timeout | null>(null);

  const getLuckActiveBtn = () => {
    Taro.showLoading({ title: "加载中...", mask: true })
    luckCardActivity().then((res) => {
      setBtnList(res.data)
      Taro.hideLoading();
    })
  }

  Taro.setBackgroundColor({
    backgroundColor: '#50009f', // 窗口的背景色为白色
  })

  // 用户可用抽奖次数
  const getCount = async () => {
    try {
      const res = await luckCardUserCount() || {}
      setUseDrawCount(res.data || 0)

    } catch (error) {

    }
  }

  // 发牌
  const cardResetHandle = () => {
    for (let i = 0; i < card.length; i++) {
      (function (j) {
          var seat = setTimeout(function () {
              cardList[j].styles = {
                ...cardList[j].styles,
                ...resetPosition[j]
              }

              setCardList([
                ...cardList
              ])

              if (j === card.length - 1)  setIsReset(true)

              clearTimeout(seat);
          }, 300 * j);
      })(i);
    }
  }

   const loopActive = () => {
      timer.current = setInterval(()=>{
        setCardIndex(preVal => (preVal+1) % 6)
      },1000)
   }

   const calcCurStyle = useCallback((curStyle, activeIndex) => {
    const backgroundUrl = cardIndex === activeIndex ? Card2: Card1
    return {
      ...curStyle,
      background: `url(${backgroundUrl}) no-repeat center / contain`
    }
   }, [cardIndex])

   // 点击支付按钮 提交订单
   const payBtnClickHandle = async ({ type: orderType }) => {
    Taro.showLoading({ title: "加载中...", mask: true })

     const { data } = await submitCardActivity({ orderType })
     if (data) {
      const { data: toPayData } = await payOrder(data)

      if (toPayData) {
        doWxPay({
          ...toPayData,
          success: () => {
            showToast('支付成功~', {
              complete: getCount
            })
          },
          fail: () => showToast('支付失败，请重新支付~')
        })
      }
    }
   }
   /**
    * @description 支付订单
    * @param bizType: 0:外卖订单  1:抽奖订单(默认外卖订单) 默认0
    */
    const payOrder = (orderNumber, bizType = 1) => {
      if (!orderNumber) return
      const params = { orderNumber, bizType }
      return wxPay(params)
    }
    interface IWxPayParams {
      timestamp: string; // 时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数，即当前的时间
      noncestr: string; // 随机字符串，长度为32个字符以下
      package: string; // 统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***
      signType?: string; // 签名算法，应与后台下单时的值一致
      sign: string; // 签名，具体见微信支付文档
      t: string;
      success?: Function;
      fail?: Function;
      complete?: Function;
     }

    const doWxPay = (params: IWxPayParams) => {
      const reqParams = {
        timeStamp: params.t,
        nonceStr: params.noncestr,
        package: params.package,
        signType: 'MD5',
        paySign: params.sign,
        success: function (res) {
          console.log('微信支付成功', res)
          params.success()
         },
        fail: function () {
          params.fail()
          // showToast('微信支付失败，请重试！')
        }
      }
      console.log('支付参数', reqParams)

      Taro.requestPayment(reqParams)
    }

  //  点击卡片
  const cardClick = (item,index) => {
    if (!isReset) return

    if (useDrawCount === 0) return showToast('您没有抽奖机会哟~')

    if (!lonAndlat.lon || !lonAndlat.lat) return showToast('获取定位信息失败~')

    doDraw({...lonAndlat, schoolId: schoolSId}).then(res => {
      setDrawResult({...res.data})
      getCount()
    })

    setIsReset(false)
    setCardIndex(-1)
    clearInterval(timer.current)

    timer.current = null
    // 当前卡片显示在屏幕正中间
    setShowCardMask(true)
    setOpenIndex(index)

    setTimeout(() => {
      setShowResult(true)
    }, 1300)
  }

  // 关闭按钮
  const closeActiviey = () => {
    setCardList([ ...card ])

    setShowResult(false)
    setOpenIndex(-1)

    setShowCardMask(false)
  }

  // 获取用户经纬度
  const getLonLat = async () => {
    // 获取用户信息
    const userInfo = await getStoregeByKey('userInfo') || {}

    if (userInfo.schoolSId) {
      setSchoolsId(userInfo.schoolSId)
    }

    if (userInfo.lon && userInfo.lat) {
      setLonAndlat({
        lon: userInfo.lon,
        lat: userInfo.lat
      })
    } else {
      userAPIAuthSeting('scope.userLocation',{},() => {
        Taro.getLocation({
          type: 'gcj02', //返回可以用于 Taro.openLocation的经纬度
          success: function (res) {
            const { latitude: lat, longitude:lon } = res
            setLonAndlat({ lat, lon })
          }
        })
      })
    }
  }

  // “我的”按钮点击事件
  const myBtnClick = ()=> {
    Taro.navigateTo({url: '/pages/coupon/index'})
  }

  const prizeName = ({prizeType: type, name = ''})=> {
    if (type === -1) return ''

    const str = prizeTypeObj[type] || ''

    const _name = name ? `${name}元` : ''
    return `${_name}${str}`
  }
  // 点击规则按钮，显示模态框
  const ruleBtnClick  = () => {
    setShowRuleModal(true)
    clearInterval(timer.current)

    timer.current = null
  }

  const ruleModalCloseHandle = () => {
    setShowRuleModal(false)
    loopActive()
  }

   useEffect(() => {
    if(isReset) loopActive()
    return () => {
      timer.current = null
    }
   }, [isReset])

   useEffect(() => {
    getLuckActiveBtn()
    getCount()

   }, [])

   useEffect(() => {
    if (!showCardMask) {
      Taro.nextTick(() => {
        setTimeout(() => {
          cardResetHandle()
        }, 1000)
      })
    }
  }, [cardResetHandle, showCardMask])

   useDidShow(() => {
    getLonLat()
   })

   return (
     <View className={styles.luckCard}>
       <View className={styles.operateBtn}>
         <View className={styles.btn} onClick={ruleBtnClick}>规则</View>
         <View className={styles.btn} onClick={myBtnClick}>我的</View>
       </View>
        <View className={styles.activeContainer}>
          <View className={styles.content}>
            <View className={styles.changeNum}>
              今日还有 <View className={styles.num}>{useDrawCount}</View> 次翻牌机会
            </View>
            <View className={styles.box}>
              {
                cardList.map((item,index) => {
                  return (
                    <View
                      className={`${styles.card} ${cardIndex === index ? styles.active : ''}  ${ openIndex === index ? styles.openCard : ''}`}
                      style={calcCurStyle(item.styles, index)}
                      key={index}
                      onClick={() => cardClick(item, index)}
                    >
                      <Image src={item.img} className={styles.cardSize}></Image>
                    </View>
                  )
                })
              }
            </View>
            <View className={styles.luky_buy}>
              {
                btnList.map((item, index) => {
                  return <View key={index} className={styles.luky_buyli} onClick={() => payBtnClickHandle(item)}>{item.desc}</View>
                })
              }

              {/* <View className={styles.luky_buyli}>5元6次</View> */}
            </View>
          </View>
        </View>
        {/* 弹出卡片蒙层 */}
        <View className={`${styles.maskCard} ${showCardMask ? styles.show : ''}`}>
          <View className={styles.maskContent} >
            <View className={`${showResult ? styles.showBlin : ''} ${styles.blin}`}></View>
            <View className={`${showResult ? styles.showCaidai : ''} ${styles.caidai}`}></View>
            <View className={`${showResult ? styles.reback : ''} ${styles.winning}`}>
              <View className={styles.redHead}></View>
              <View className={styles.redbody}>
                {
                  drawResult.prize ? <View className={styles.title}>恭喜你，中奖啦~</View> : <View className={styles.title}>很遗憾，未中奖</View>
                }
              </View>

              <View className={`${showResult ? styles.pull : ''} ${styles.card}`}>
                {
                  drawResult.prize
                  ? <View className={styles.resultBg}>{prizeName(drawResult)}</View>
                  : <View className={styles.resultBg}>再接再厉</View>
                }
              </View>

              <Image src={CloseIcon} className={styles.close} onClick={closeActiviey}></Image>
            </View>
          </View>
        </View>
        {/* 活动规则 */}
        <RuleModal show={showRuleModal} onClose={ruleModalCloseHandle} />
     </View>
   );
 }

 export default LuckCard
